package leo.mystudy.utils;

import leo.mystudy.pojo.TreeNode;

/**
 * @author leo
 * @version 1.0.0
 * @description
 * @create 2022/3/15 14:18
 */
public class TreeNodeUtils {

    /**
     * 根据值数组构建一个完全二叉树
     *
     * @param arr 值数组
     * @return 完全二叉树
     */
    public static TreeNode buildTreeNode(Integer[] arr) {
        return doBuildTreeNode(arr, 0);
    }

    public static void prePrintTreeNode(TreeNode treeNode) {
        if (treeNode == null) {
            return;
        }
        System.out.println(treeNode.val);
        prePrintTreeNode(treeNode.left);
        prePrintTreeNode(treeNode.right);
    }

    private static TreeNode doBuildTreeNode(Integer[] arr, int index) {
        if (index >= arr.length || arr[index] == null) {
            return null;
        }
        TreeNode node = new TreeNode(arr[index]);
        node.left = doBuildTreeNode(arr, index * 2 + 1);
        node.right = doBuildTreeNode(arr, index * 2 + 2);
        return node;
    }

    public static void main(String[] args) {
        TreeNode node = buildTreeNode(new Integer[]{1, 3, null, 5, 7, null, null, null, 10});
        prePrintTreeNode(node);
    }
}
